#include "net/EventLoopThreadPool.h"
#include "net/EventLoopThread.h"
#include "net/EventLoop.h"
#include <cassert>

namespace toym
{
namespace net
{

EventLoopThreadPool::EventLoopThreadPool(EventLoop* loop)
    : m_baseLoop(loop),
      m_started(false),
      m_nThread(0),
      m_next(0),
      m_threads(),
      m_loops()
{
}

EventLoopThreadPool::~EventLoopThreadPool() = default;

void EventLoopThreadPool::start(ThreadInitCallback_t cb) {
    if (m_started == false) {
        m_started = true;
        if (m_nThread > 0) {
            for (int i = 0; i < m_nThread; ++i) {
                std::unique_ptr<EventLoopThread> p(new EventLoopThread(cb));
                m_loops.push_back(p->startLoop());
                m_threads.emplace_back(std::move(p));
            }
        }
        m_next = 0;
    }
}

EventLoop* EventLoopThreadPool::nextLoop() {
    EventLoop* ret = m_baseLoop;
    if (!m_loops.empty()) {
        ret = m_loops[m_next++];
        if (static_cast<std::size_t>(m_next) >= m_loops.size()) {
            m_next = 0;
        }
    }
    return ret;
}

} // namespace net

} // namespace toym
